#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/9/17 14:13
# @Author  : youfeng

import demjson
import redis

from ext.redis_key_wrap import RedisKeyWrap


class RedisResultHandler(object):
    def __init__(self, host, port, password, db, max_connections, log):
        self.log = log
        self.__redis_client = redis.StrictRedis(host=host,
                                                port=port,
                                                password=password,
                                                db=db,
                                                max_connections=max_connections)

    def __get_redis_value(self, key):
        result_str = self.__redis_client.get(key)
        if result_str is None:
            return None

        try:
            result = demjson.decode(result_str)
        except Exception as e:
            self.log.error("json 格式转换失败: key = {}".format(key))
            self.log.exception(e)
            return -1

        return result

    def get_gsxt_result(self, company):
        key = RedisKeyWrap.get_gsxt_result_key(company)
        return self.__get_redis_value(key)

    def get_wenshu_result(self, company):
        key = RedisKeyWrap.get_wenshu_result_key(company)
        return self.__get_redis_value(key)

    def get_news_result(self, company):
        key = RedisKeyWrap.get_news_result_key(company)
        return self.__get_redis_value(key)

    def get_zhixing_result(self, company):
        key = RedisKeyWrap.get_zhixing_result_key(company)
        return self.__get_redis_value(key)

    def get_shixin_result(self, company):
        key = RedisKeyWrap.get_shixin_result_key(company)
        return self.__get_redis_value(key)
